﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Specialized;

namespace Odyssey.Controls
{
    public interface ICollectionChangedListener
    {
        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e);
    }


    /// <summary>
    /// Listens to an INotifyCollectionChanged event and creates a weak reference to the target which receives the event.
    /// </summary>
    public class WeakCollectionChangedListener
    {
        private INotifyCollectionChanged source;
        private WeakReference weakListener;

        private WeakCollectionChangedListener(INotifyCollectionChanged source, ICollectionChangedListener listener)
        {
            this.source = source;
            this.source.CollectionChanged+=new NotifyCollectionChangedEventHandler(this.SourceCollectionChanged);
            this.weakListener = new WeakReference(listener);
        }

        public static WeakCollectionChangedListener CreateIfNecessary(object source, ICollectionChangedListener listener)
        {
            if (source is INotifyCollectionChanged)
            {
                return new WeakCollectionChangedListener(source as INotifyCollectionChanged, listener);
            }
            return null;
        }

 

        /// <summary>
        /// Disconnects the listener from the event.
        /// </summary>
        public void Disconnect()
        {
            if (this.source != null)
            {
                this.source.CollectionChanged -= SourceCollectionChanged;
                this.source = null;
                this.weakListener = null;
            }
        }

        private void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (this.weakListener != null)
            {
                ICollectionChangedListener target = this.weakListener.Target as ICollectionChangedListener;
                if (target != null)
                {
                    target.OnCollectionChanged(sender, e);
                }
                else
                {
                    this.Disconnect();
                }
            }
        }


    }
}
